<?php

namespace App\Store\Controllers\OldMaterial;

use App\Common\Services\CommonExcelExport;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\Goods\GoodsStockList;
use App\Store\Models\OldMaterial\Stock;
use App\Store\Models\Order\OrderSalesGoods;
use App\Store\Services\Goods\Goods;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Validate\OldMaterial\Stock as ValidateOldMaterialStock;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

/**
 * 旧料库存
 * 1.销售开单【换货方式回收】、2.纯回收开单、3.商品库存转旧料
 * 换货金额，只有2有
 * 状态：返厂、调拨、XX等三种
 * 回收方式：按克
 * 物料，基础设置-金价管理列表-商品类别 old_recovery_price
 */
class StockController extends Controller
{
    /**
     * 列表
     */
    public function getlist(Request $request)
    {
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $request['cp_id'] = $cp_id;
        $list = Stock::getList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 汇总列表
     */
    public function getsummarylist(Request $request)
    {
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $request['cp_id'] = $cp_id;
        $list = Stock::getSummaryList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 明细导出
     */
    public function doexport(Request $request)
    {
        $list = Stock::getList($request)['list'];

        $row = [
            ['table_header' => '旧料库存明细'],
            [
                'store_name' => '回收门店',
                'order_sncode' => '订单号',
                'create_at' => '回收时间',
                'stock_type' => '回收方式',
                'goods_sn_code' => '条码',
                'goods_category_id' => '旧料类别',
                'count' => '数量',
                'piece_weight' => '重量',
                'piece_weight_new' => '实重',
                'stock_status' => '状态',
                'cf_no' => '证书号',
                'goods_brand_id' => '品牌',
                'goods_pricetype_id' => '价格类型',
                'main_stone_weigth' => '主石重',
                'main_stone_count' => '主石数',
                'other_stone_weigth' => '副石重',
                'other_stone_count' => '副石数',
                'color' => '颜色',
                'clarity' => '净度',
                'exchange_amount' => '换货金额',
            ]];

        //返厂金价、旧料估值、回收金额

        $exceldata = [];
        foreach ($list as $val) {
            switch ($val['stock_status']) {
                case 1:
                    $stock_status = '在库';
                    break;
                case 2:
                    $stock_status = '调拨中';
                    break;
                case 3:
                    $stock_status = '调拨';
                    break;
                case 4:
                    $stock_status = '返厂中';
                    break;
                case 5:
                    $stock_status = '返厂';
                    break;
                case 6:
                    $stock_status = '上柜';
                    break;
            }
            $exceldata[] = [
                'store_name' => $val['storeinfo']['store_name'],
                'order_sncode' => $val['order_sncode'],
                'create_at' => date('Y-m-d H:i:s', $val['create_at']),
                'stock_type' => ($val['stock_type'] == 1) ? '按克' : '标价',
                'goods_sn_code' => $val['goods_sn_code'],
                'goods_category_id' => $val['goods_category']['category_name'],
                'count' => $val['count'],
                'piece_weight' => $val['piece_weight'],
                'piece_weight_new' => $val['piece_weight_new'],
                'stock_status' => $stock_status,
                'cf_no' => $val['cf_no'],
                'goods_brand_id' => $val['storeinfo']['store_name'],
                'goods_pricetype_id' => '价格类型',
                'main_stone_weigth' => $val['main_stone_weigth'],
                'main_stone_count' => $val['main_stone_count'],
                'other_stone_weigth' => $val['other_stone_weigth'],
                'other_stone_count' => $val['other_stone_count'],
                'color' => $val['color'],
                'clarity' => $val['clarity'],
                'exchange_amount' => $val['exchange_amount'],
            ];
        }

        $filename = '旧料库存明细信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }

    /**
     * 汇总导出
     */
    public function dosummaryexport(Request $request)
    {
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $request['cp_id'] = $cp_id;
        $list = Stock::getSummaryList($request)['list'];

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        if (in_array($accountinfo['type'], [1])) {
            $row = [
                ['table_header' => '旧料库存汇总'],
                [
                    'store_name' => '回收门店',
                    'goods_category_id' => '旧料类别',
                    'count' => '件数',
                    'piece_weight' => '重量',
                    'piece_weight_new' => '实重',
                    'exchange_amount' => '换货金额',
                ]];
        } else {
            $row = [
                ['table_header' => '旧料库存汇总'],
                [
                    'store_name' => '回收门店',
                    'goods_category_id' => '旧料类别',
                    'count' => '件数',
                    'piece_weight' => '重量',
                    'piece_weight_new' => '实重',
                    'exchange_amount' => '换货金额',
                    'valuations' => '旧料估值'
                ]];
        }

        $exceldata = [];
        $count = $piece_weight = $piece_weight_new = $exchange_amount = $valuations = 0;
        foreach ($list as $val) {
            if (in_array($accountinfo['type'], [1])) {
                $exceldata[] = [
                    'store_name' => $val['storeinfo']['store_name'],
                    'goods_category_id' => $val['goods_category']['category_name'],
                    'count' => $val['count'],
                    'piece_weight' => $val['piece_weight'],
                    'piece_weight_new' => $val['piece_weight_new'],
                    'exchange_amount' => $val['exchange_amount'] / 100,
                ];
            } else {
                $exceldata[] = [
                    'store_name' => $val['storeinfo']['store_name'],
                    'goods_category_id' => $val['goods_category']['category_name'],
                    'count' => $val['count'],
                    'piece_weight' => $val['piece_weight'],
                    'piece_weight_new' => $val['piece_weight_new'],
                    'exchange_amount' => $val['exchange_amount'] / 100,
                    'valuations' => $val['valuations'] / 100,
                ];
            }
            $count += $val['count'];
            $piece_weight += $val['piece_weight'];
            $piece_weight_new += $val['piece_weight_new'];
            $exchange_amount += $val['exchange_amount'];
            $valuations += $val['valuations'];
        }
        if (in_array($accountinfo['type'], [1])) {
            $exceldata[] = [
                'store_name' => '总计',
                'goods_category_id' => '',
                'count' => $count,
                'piece_weight' => $piece_weight,
                'piece_weight_new' => $piece_weight_new,
                'exchange_amount' => $exchange_amount / 100,
            ];
        } else {
            $exceldata[] = [
                'store_name' => '总计',
                'goods_category_id' => '',
                'count' => $count,
                'piece_weight' => $piece_weight,
                'piece_weight_new' => $piece_weight_new,
                'exchange_amount' => $exchange_amount / 100,
                'valuations' => $valuations / 100,
            ];
        }


        $filename = '旧料库存汇总信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata, [], [], false), $filename);
    }

    /**
     * 编辑
     */
    public function dopostedit(Request $request)
    {
        $req_data = $request->only(['id', 'goods_sn_code', 'piece_weight_new', 'remark']);
        $Validate = new ValidateOldMaterialStock('edit');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        Stock::where('id', $req_data['id'])->update([
            'goods_sn_code' => $req_data['goods_sn_code'],
            'piece_weight_new' => $req_data['piece_weight_new'],
            'remark' => $req_data['remark'] ?? '',
            'update_at' => time()
        ]);
        return response()->json(['code' => '000', 'msg' => '编辑成功']);
    }

    /**
     * 删除
     */
    public function dopostdel(Request $request)
    {
        $req_data = $request->only(['id']);
        $Validate = new ValidateOldMaterialStock('del');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        Stock::where('id', $request['id'])->update([
            'is_del' => 2,
            'del_at' => time()
        ]);
        return response()->json(['code' => '000', 'msg' => '删除成功']);
    }

    /**
     * 上柜
     */
    public function oncounter(Request $request)
    {
        $req_data = $request->only(['id']);
        $Validate = new ValidateOldMaterialStock('oncounter');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $oldStockOne = Stock::where('id', $request['id'])->first();
        if (empty($oldStockOne)) {
            return response()->json(['code' => '001', 'msg' => '旧料商品不存在不能上柜']);
        }
        $oldStockOne = $oldStockOne->toArray();

        if((int)$oldStockOne['type']!==3){
            $order = OrderSalesGoods::query()
                ->where(['goods_sn_code' => $oldStockOne['goods_sn_code'], 'is_del' => 1])
                ->first();
            if (empty($order)) {
                return response()->json(['code' => '001', 'msg' => '非本厂不能上柜']);
            }
        }

        $where = [
            'cp_id' => $oldStockOne['cp_id'],
            'store_id' => $oldStockOne['store_id'],
            'goods_sn_code' => $oldStockOne['goods_sn_code'],
            'is_del' => 1
        ];
        $stockOne = GoodsStockList::query()->where($where)->first();
        if (empty($stockOne)) {
            return response()->json(['code' => '001', 'msg' => '非本厂不能上柜']);
        }

        $stockOne = $stockOne->toArray();

        $stockInfo = $stockOne;

        $category = GoodsCategory::query()
            ->where('cp_id', $oldStockOne['cp_id'])
            ->where('store_id', $oldStockOne['store_id'])
            ->where('is_del', 1)
            ->where('id', $stockOne['goods_category_id'])
            ->first();

        if (empty($category)) {
            return response()->json(['code' => '001', 'msg' => '商品类别不存在']);
        }

        $category = $category->toArray();

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        Stock::where('id', $request['id'])->update([
            'stock_status' => 6,
            'is_del' => 2,
            'update_account_id' => $accountinfo['id'],
            'update_account_real_name' => $accountinfo['real_name'],
            'update_at' => time(),
        ]);

        $stockOne['count'] = $stockOne['count'] + $oldStockOne['count'];
        if ($stockOne['is_code_more'] == 1) {
            if ($stockOne['netglod_weight'] > 0) {
                $oldStockOne['total_netglod_weight'] = $oldStockOne['netglod_weight'] ?? 0;
            }
            if ($stockOne['piece_weight'] > 0) {
                $oldStockOne['total_piece_weight'] = $oldStockOne['piece_weight'] ?? 0;
            }

            $total_piece_weight = $stockOne['count'] * $stockOne['piece_weight'];
            $total_netglod_weight = $stockOne['count'] * $stockOne['netglod_weight'];

        } else {
            // 如果是一码多货，此处都是取piece_weight字段
            $oldStockOne['total_netglod_weight'] = $oldStockOne['piece_weight'] ?? 0;
            $total_netglod_weight = $stockOne['total_netglod_weight'] + $oldStockOne['total_netglod_weight'];
        }


        list($total_cost_fee, $costglod_price, $piececost_fee) = (new Goods())->incrTotalCost($stockInfo, $oldStockOne, $category['is_gram']);

        //  $total_cost_fee = (new Goods())->computeOriginalTotalCost($stockOne, $category['is_gram']);
        GoodsStockList::where($where)->update([
            'count' => $stockOne['count'],
            'total_piece_weight' => $total_piece_weight ?? 0,
            'total_netglod_weight' => $total_netglod_weight ?? 0,
            'total_cost_fee' => $total_cost_fee,
            'costglod_price' => $costglod_price,
            'piececost_fee' => $piececost_fee
        ]);

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }
}
